package com.aijk.web.admin.controller.ehm.company;


import com.aijk.commons.exception.ErrorCodeException;
import com.aijk.commons.lang.utils.StringUtil;
import com.aijk.commons.utils.PasswordHelper;
import com.aijk.commons.utils.Utils;

import com.aijk.ehm.api.EhmCompanyApi;
import com.aijk.ehm.model.EhmCompany;
import com.aijk.ehm.model.dto.EhmCompanyDto;
import com.aijk.ehm.model.qo.EhmCompanyQo;
import com.aijk.ehm.model.vo.EhmCompanyVo;
import com.aijk.ehm.sys.api.SysAdminApi;
import com.aijk.ehm.sys.api.SysAdminRoleApi;
import com.aijk.ehm.sys.api.SysRoleApi;
import com.aijk.ehm.sys.model.SysAdmin;
import com.aijk.ehm.sys.model.SysAdminRole;
import com.aijk.ehm.sys.model.SysRole;
import com.aijk.ehm.sys.model.qo.AdminRoleQo;
import com.aijk.ehm.sys.model.qo.SysAdminQo;
import com.aijk.ehm.sys.model.qo.SysRoleQo;
import com.aijk.web.admin.RetMsg;
import com.aijk.web.admin.controller.BaseController;
import com.aijk.web.admin.entity.Constant;
import com.aijk.web.admin.utils.ConvertUtil;
import com.aijk.web.admin.utils.DataTableUtil;
import com.aijk.web.admin.utils.RandomString;
import com.github.pagehelper.PageInfo;
import org.apache.shiro.authz.annotation.RequiresPermissions;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Controller;
import org.springframework.ui.Model;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestMethod;
import org.springframework.web.bind.annotation.RequestParam;
import org.springframework.web.bind.annotation.ResponseBody;

import javax.validation.Valid;
import java.util.Date;
import java.util.HashMap;
import java.util.List;

/**
 * 企业Controller
 */
@Controller
@RequestMapping("/admin/ehm/company")
public class CompanyController extends BaseController {

    protected Logger logger = LoggerFactory.getLogger(this.getClass());
    @Autowired
    private EhmCompanyApi ehmCompanyApi;
    @Autowired
    private SysAdminApi sysAdminApi;
    @Autowired
    private SysRoleApi roleApi;
    @Autowired
    private SysAdminRoleApi adminRoleApi;

    @RequestMapping(value = "/list", method = RequestMethod.GET)
    public String list_view() {
        return "ehm/company/list";
    }

    /**企业列表**/
    @RequestMapping(value = "/list", method = RequestMethod.POST)
    @RequiresPermissions("admin:ehm:company:list")
    @ResponseBody
    public RetMsg list(@RequestParam HashMap skey, @RequestParam(value = "draw", defaultValue = "1") Integer draw) {
        Long iTotalRecords;
        DataTableUtil.FormatOptions(skey);
        if (Utils.isNotEmpty(skey.get("orderbyclause"))) {
            skey.put("orderbyclause", StringUtil.toUnderlineCase(Utils.toString(skey.get("orderbyclause"))));
        }
        EhmCompanyQo qo = DataTableUtil.fillQo(skey,EhmCompanyQo.class);
        PageInfo<EhmCompanyVo> peCenterVoPageInfo = ehmCompanyApi.page(qo);
        iTotalRecords =peCenterVoPageInfo.getTotal();
        RetMsg regMsg = new RetMsg();
        regMsg.put("data",   peCenterVoPageInfo.getList());
        regMsg.put("draw", draw);
        regMsg.put("recordsTotal", iTotalRecords);
        regMsg.put("recordsFiltered", iTotalRecords);

        return regMsg;
    }

    /**企业新增、编辑**/
    @RequestMapping(value = "/edit", method = RequestMethod.GET)
    public String add_view(Model model, Long id) {
            EhmCompanyVo ehmCompanyVo = new EhmCompanyVo();
        if (id != null){
            ehmCompanyVo = ehmCompanyApi.findOne(id);
            SysAdmin sysAdmin = sysAdminApi.findByUsername(ehmCompanyVo.getUsername());
            AdminRoleQo arqo=new AdminRoleQo();
            arqo.setAdminId(sysAdmin.getAdminId());
            List<SysAdminRole> adminRoles = adminRoleApi.getList(arqo);
            String rids ="";
            for(SysAdminRole adminRole:adminRoles){
                rids+=adminRole.getRoleId()+",";
            }
            if(rids.length()>0){
                model.addAttribute("rids",rids.substring(0,rids.length()-1));
            }
        }
        SysRoleQo qo= new SysRoleQo();
        qo.setSysFlag(Constant.SYS_PE_FLAG);
        List<SysRole> roles = roleApi.getList(qo);
        model.addAttribute("roles",roles);
        model.addAttribute("sys_flag",true);//sys_flag 系统标识 true：系统管理员 false:企业自身登录
        model.addAttribute("company",ehmCompanyVo);
        return "ehm/company/edit";
    }

    /**企业信息**/
    @RequestMapping(value = "/info/edit", method = RequestMethod.GET)
    public String info(Model model) {
        if(isSubCompany()){
            if(isCompany()){
                return "error/no_permissions";
            }

            EhmCompanyVo peCenterVo = ehmCompanyApi.findOne(getCurrentUser().getCompanyId());
            SysAdmin sysAdmin = sysAdminApi.findByUsername(peCenterVo.getUsername());
            AdminRoleQo arqo=new AdminRoleQo();
            arqo.setAdminId(sysAdmin.getAdminId());
            List<SysAdminRole> adminRoles = adminRoleApi.getList(arqo);
            String rids ="";
            for(SysAdminRole adminRole:adminRoles){
                rids+=adminRole.getRoleId()+",";
            }
            if(rids.length()>0){
                model.addAttribute("rids",rids.substring(0,rids.length()-1));
            }
            SysRoleQo qo= new SysRoleQo();
            qo.setSysFlag(Constant.SYS_PE_FLAG);
            List<SysRole> roles = roleApi.getList(qo);
            model.addAttribute("roles",roles);
            model.addAttribute("sys_flag",false);//sys_flag 系统标识 true：系统管理员 false:企业自身登录
            model.addAttribute("company",peCenterVo);
            return "ehm/company/edit";
        }else{
            return "error/no_permissions";
        }
    }

    @RequestMapping(value = "/save", method = RequestMethod.POST)
    @ResponseBody
    public RetMsg save(EhmCompanyDto dto, @RequestParam(value = "roles") String roles) {
        try {
            if (dto.getId() == null){
                SysAdmin admin = sysAdminApi.findByUsername(dto.getUsername());
                if (admin != null) {
                    return RetMsg.failed("管理员账号已经存在");
                }
                dto.setSn(ConvertUtil.randomString(13));
                dto.setStatus((byte)10);
                dto.setCreated(new Date());
                dto.setCreater(Utils.toLong(getCurrentUser().getAdminId()));
                Long peId = ehmCompanyApi.save(dto);
                addSysAdmin(peId,dto,roles);//新增账号
            }else {
                dto.setModifier(Utils.toLong(getCurrentUser().getAdminId()));
                dto.setModified(new Date());
                ehmCompanyApi.update(dto);
                SysAdmin sysAdmin = sysAdminApi.findByUsername(dto.getUsername());
                sysAdminApi.update(sysAdmin,roles);
            }
        }catch (ErrorCodeException e){
            e.printStackTrace();
            return RetMsg.failed();
        }
        return RetMsg.success();    }


    /**禁用、启用**/
    @RequestMapping(value = "/status", method = RequestMethod.POST)
    @ResponseBody public RetMsg status(@Valid EhmCompanyDto dto) {
        try {
            dto.setModifier(Utils.toLong(getCurrentUser().getAdminId()));
            dto.setModified(new Date());
            ehmCompanyApi.update(dto);
        }catch (ErrorCodeException e){
            e.printStackTrace();
            return RetMsg.failed();
        }
        return RetMsg.success();
    }

    @RequestMapping(value = "/validations", method = RequestMethod.POST)
    @ResponseBody
    public RetMsg validation(String validation , Long id) {
        RetMsg msg = new RetMsg();
        try {
            EhmCompanyQo ehmCompanyQo = new EhmCompanyQo();
            ehmCompanyQo.setSn(validation);
            List<EhmCompanyVo> vo = ehmCompanyApi.list(ehmCompanyQo);

            if(id == 0){
                if(vo != null && vo.size() > 0){
                    msg.put("msg" , "该编码已被占用");
                }else{
                    msg.put("msg" , "可以使用该编码");
                }
            }else{
                if(vo != null && vo.size() > 0){
                    if(id == vo.get(0).getId() ){
                        msg.put("msg" , "可以使用该编码");
                    }else{
                        msg.put("msg" , "该编码已被占用");
                    }
                }else{
                    msg.put("msg" , "可以使用该编码");
                }
            }
            msg.put("code" , 0);
        }catch (ErrorCodeException e){
            e.printStackTrace();
            msg.put("code" , -1);
        }
        return msg;
    }

    /**密码重置**/
    @RequestMapping(value = "/resetPass", method = RequestMethod.POST)
    @ResponseBody public RetMsg resetPass(@Valid SysAdminQo sysAdminQo) {
        try {
            sysAdminApi.resetPass(sysAdminQo);
        }catch (ErrorCodeException e){
            e.printStackTrace();
            return RetMsg.failed();
        }
        return RetMsg.success();
    }

    private void addSysAdmin(Long companyId, EhmCompanyDto dto,String roles){
        //创建登录账号
        SysAdmin sysAdmin = new SysAdmin();
        sysAdmin.setSysFlag(Constant.SYS_PE_FLAG);
        sysAdmin.setCompanyId(companyId);
        sysAdmin.setUsername(dto.getUsername());
        sysAdmin.setName(dto.getTitle());
        sysAdmin.setTel(dto.getPhone());
        sysAdmin.setSalt(RandomString.generateRandomString(16));
        sysAdmin.setPassword(PasswordHelper.encryptPassword("123456", sysAdmin.getSalt()));
        sysAdmin.setAdminType((short)2);
        sysAdmin.setAdminState((short)0);
        sysAdmin.setCreateTime(new Date());
        sysAdminApi.save(sysAdmin,roles);
    }
}
